package Usermanagement

import (
	"database/sql"
	"fmt"
	"log"
)

func deleUserDBconnect(db *sql.DB, userID int) error {
	query := `DELETE FROM Manager_users WHERE id = $1`
	result, err := db.Exec(query, userID)
	if err != nil {
		return fmt.Errorf("数据库操作失败: %v", err)
	}
	
	rowsAffected, _ := result.RowsAffected()
	if rowsAffected == 0 {
		return fmt.Errorf("用户ID %d 不存在", userID)
	}
	return nil
}

func DeletUser() {
	GetAlluser()
	var index_user_data int
	var select_number_bool string
	db, err := ConnectDB()
	if err != nil {
		log.Fatal("数据库连接失败:", err)
	}
	defer db.Close()

	for {
		fmt.Println("请输入你要删除的用户序号：")
		fmt.Scan(&index_user_data)
		
		err := deleUserDBconnect(db, index_user_data)
		if err != nil {
			fmt.Println(err)
			continue
		}
		
		fmt.Printf("用户%d已删除\n", index_user_data)
		index_user_data = 0  // 重置用户序号
		
		// 询问是否返回
		fmt.Print("是否返回上一层[y/n]：")
		fmt.Scan(&select_number_bool)
		if select_number_bool == "y" {
			break
		} else if select_number_bool != "n" {
			fmt.Println("输入无效，默认返回主菜单")
			break
		}
	}
}
